<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-col :span="5">
          <el-form-item label="用电企业">
            <FilterSelect2
              v-model="bizOrgNo"
              :optionlist="companyList"
              :valuekey="{ name: 'name', value: 'id' }"
              @changeSelect="companyChange"
            ></FilterSelect2>
          </el-form-item>
        </el-col>
        <el-col :span="19" style="text-align: right">
          <el-form-item>
            <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="titlebox">
        <div class="text"></div>
        <div style="flex: 1; text-align: right; margin-right: 10px">
          <el-button type="primary" size="small" @click="add('add')"
            ><i class="el-icon-plus">新增</i></el-button
          >
        </div>
        <TopTile
          @command="command"
          @daochu="daochu"
          @shuaxin="shuaxin"
        ></TopTile>
      </div>
      <div class="table-content">
        <template>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="150"
            >
            </el-table-column>
            <el-table-column prop="companyName" label="用电企业">
            </el-table-column>
            <el-table-column prop="departmentName" label="所属部门">
            </el-table-column>
            <el-table-column prop="teamCode" label="班组编码">
            </el-table-column>
            <el-table-column prop="teamName" label="班组名称">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="230">
              <template slot-scope="scope">
                <div class="operate">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="编辑"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-edit"
                      @click="handleEdit(scope.row)"
                    ></i
                  ></el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <i
                      style="font-size: 14px; color: red; cursor: pointer"
                      class="el-icon-delete"
                      @click="handleDel(scope.row)"
                    ></i
                  ></el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="fenye">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page.sync="pageobj._pageNo"
            @current-change="currentChange"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <div class="dialog">
      <div class="dialog">
        <el-dialog
          :title="isEdit === 'add' ? '新增班组' : '修改班组'"
          :visible.sync="DialogVisible"
          v-if="DialogVisible"
          label-position="left"
          width="400px"
          :destroy-on-close="true"
          :close-on-click-modal="false"
          :before-close="beforeClose"
        >
          <el-form
            :rules="rules"
            ref="form"
            :model="dialogForm"
            label-width="80px"
          >
            <el-form-item label="企业名称" prop="companyId">
              <FilterSelect2
                size="large"
                v-model="dialogForm.companyId"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
              ></FilterSelect2>
            </el-form-item>
            <el-form-item label="所属部门" prop="departmentId">
              <FilterSelect2
                size="large"
                v-model="dialogForm.departmentId"
                :optionlist="departmentList"
                :valuekey="{ name: 'departmentName', value: 'id' }"
                placeholder="请选择所属部门"
              ></FilterSelect2>
            </el-form-item>
            <el-form-item label="班组编码" prop="teamCode">
              <el-input
                v-model="dialogForm.teamCode"
                placeholder="请输入班组编码"
              ></el-input>
            </el-form-item>
            <el-form-item label="班组名称" prop="teamName">
              <el-input
                v-model="dialogForm.teamName"
                placeholder="请输入班组名称"
              ></el-input>
            </el-form-item>
          </el-form>
          <div style="margin-top: 10px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="beforeClose">取 消</el-button>
              <el-button type="primary" @click="submit">保 存</el-button>
            </span>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
// import { saveAs } from 'file-saver'
import { getCompanyListApi } from '@/api/Configuration-management/index'
import {
  addListApi,
  delListApi,
  editListApi,
  getListApi,
  getDepartmentListApi
} from '@/api/Configuration-management/group-maintain'
import { exportexcel } from '@/utils/excel'
import FilterSelect2 from '@/components/FilterSelect2/index.vue'
import TopTile from '@/components/TopTitle/index.vue'
import Twobtn from '@/components/Twobtn/index.vue'

export default {
  name: 'DepartmentMaintain',
  components: {
    FilterSelect2,
    TopTile,
    Twobtn
  },
  data() {
    return {
      dataList: [],
      enterpriseCode: '',
      id: '',
      bizOrgNo: '',
      isEdit: 'add',
      dizhi: '',
      DialogVisible: false,
      form: { alarmLevel: '0' },
      rules: {
        companyId: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        departmentId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        teamCode: [
          { required: true, message: '请输入班组编码', trigger: 'blur' }
        ],
        teamName: [{ required: true, message: '请输班组名称', trigger: 'blur' }]
      },
      statusList: [],
      dialogForm: {},
      address: '',
      isshow: false,
      isheight: 72,
      date: [],
      iissize: 'medium',
      // HYFL: [],
      loading: false,
      tableData: [],
      total: 0,
      pageobj: {
        _pageNo: 0,
        _pageSize: 10
      },
      progress: 1,
      addType: '',
      companyData: {},
      companyList: [],
      departmentList: [] // 部门列表
    }
  },

  async mounted() {
    await this.getCompanyList()
    await this.getDepartmentList()
    await this.getdatalist()
  },
  methods: {
    companyChange(val) {
      if (val) {
        localStorage.setItem('companyId', val)
      }
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi({ companyId: this.bizOrgNo })
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.bizOrgNo = companyId
      } else {
        this.bizOrgNo = this.companyList[0].id
      }
    },
    // 获取部门列表
    async getDepartmentList() {
      try {
        const res = await getDepartmentListApi({
          companyId: this.bizOrgNo,
          pageNo: 0,
          pageSize: 1000 // 获取所有部门
        })
        if (res.code === 200) {
          this.departmentList = res.data.list || []
        }
      } catch (error) {
        console.error('获取部门列表失败:', error)
        this.departmentList = []
      }
    },
    // 初始化
    async getchushihua() {
      this.bizOrgNo = this.companyList[0].id
    },
    // 获取数据
    async getdatalist() {
      this.loading = true
      const res = await getListApi({
        companyId: this.bizOrgNo,
        pageNo: this.pageobj._pageNo - 1,
        pageSize: 10
      })
      console.log(res)
      this.tableData = res.data.list
      this.total = res.data.totalCount
      console.log(this.total)
      this.loading = false
    },
    // 分页查询
    currentChange() {
      this.getdatalist()
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist('')
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    chaxun() {
      // console.log(this.dataList)
      this.getdatalist()
    },
    // 导出
    daochu() {
      exportexcel(
        '/ecm-microservice-biz/ecm/team/set/export',
        {
          companyId: this.bizOrgNo
        },
        '班组维护'
      )
    },
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    async submit() {
      await this.$refs.form.validate()
      const res =
        this.isEdit === 'add'
          ? await addListApi(this.dialogForm)
          : await editListApi(this.dialogForm)
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: this.isEdit === 'add' ? '新增成功' : '修改成功',
          duration: 2000
        })
        this.getdatalist()
        this.beforeClose()
      } else {
        this.$message({
          type: 'error',
          message: this.isEdit === 'add' ? '新增失败' : '修改失败',
          duration: 2000
        })
      }
      console.log(res)
    },
    async chongzhi() {
      await this.getchushihua()
      this.date = []
      this.enterpriseCode = ''
      this.dataList = []
      this.getdatalist('')
      this.form.alarmLevel = '0'
      // 重新获取部门列表
      await this.getDepartmentList()
    },
    // 编辑
    async handleEdit(row) {
      console.log(row)
      this.isEdit = 'edit'
      this.$set(this.dialogForm, 'companyId', row.companyId)
      this.$set(this.dialogForm, 'departmentId', row.departmentId)
      this.$set(this.dialogForm, 'teamCode', row.teamCode)
      this.$set(this.dialogForm, 'teamName', row.teamName)
      this.$set(this.dialogForm, 'id', row.id)
      this.DialogVisible = true
    },
    async add(type) {
      this.isEdit = type
      this.$set(this.dialogForm, 'companyId', this.companyList[0].id)
      this.$set(
        this.dialogForm,
        'departmentId',
        this.departmentList[0]?.id || ''
      )
      this.$set(this.dialogForm, 'teamCode', '')
      this.$set(this.dialogForm, 'teamName', '')
      this.DialogVisible = true
    },
    next(progress, id) {
      this.progress = progress
      if (id) {
        this.id = id
      }
    },
    fileData(data) {
      this.companyData = data
      this.dizhi = data.companyAddress
    },
    beforeClose() {
      this.DialogVisible = false
      this.dialogForm = {}
      this.isEdit = 'add'
    },
    finish() {
      this.centerDialogVisible = false
      this.progress = 1
      this.id = ''
      this.getdatalist('')
    },
    // 删除
    async handleDel(item) {
      this.$confirm('此操作将永久删除该班组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delListApi(item.id)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功',
              duration: 2000
            })
            this.getdatalist()
            this.beforeClose()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 2000
            })
          }
        })
        .catch((action) => {
          if (action === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
.option {
  height: auto;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.bigbox {
  background-color: #f1f1f1;
  padding: 10px;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
    // transition-property: all;
    // transition-duration: 0.2s;
  }
  .bodybox {
    background-color: #fff;
    margin-top: 10px;
    padding: 20px 20px 20px 20px;
    height: 90%;
    .titlebox {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .text {
        font-weight: bold;
        font-size: 18px;
      }
      .right {
        align-items: center;
        i {
          margin-left: 10px;
        }
      }
    }
    .fenye {
      margin-top: 15px;
      text-align: right;
    }
  }
}

.operate {
  display: flex;
  justify-content: space-around;
}
.dialogBtn {
  width: 80px;
  height: 40px;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
  align-items: center;
}
::v-deep.dialog {
  .el-dialog {
    width: 800px;
    // height: 550px;
    // padding-left: 10px;
    .el-dialog__header {
      padding: 20px 0;
      padding-left: 20px;
      font-size: 14px;
      text-align: left !important;
      border-bottom: 1px solid #f7f7f7;
    }
    // .el-dialog__body {
    //   line-height: 10px;
    //   padding-bottom: 15px;
    // }
    .el-dialog__footer {
      margin-top: 50px;
      height: 60px;
    }
  }
  //   .el-row {
  //     height: 55px;
  //     .el-col {
  //       height: 55px;
  //     }
  //   }
}

::v-deep.el-date-editor {
  .el-range-separator {
    line-height: 22px;
  }
}

::v-deep.dialog-content {
  .el-form-item__error {
    margin-top: -8px;
  }
  .el-form-item {
    height: 50px;
    .el-form-item__content {
      width: 90%;
      .el-select {
        width: 100%;
      }
    }
    .el-form-item__label {
      padding: 0;
      padding-right: 10px;
      padding-top: 3px;
      line-height: 32px;
    }
    margin-bottom: 5px;
  }
}
::v-deep.checkbox-item {
  border-top: 1px solid #f7f7f7;
  border-bottom: 1px solid #f7f7f7;
  margin-top: 20px;
  padding: 20px 0;
  .el-form-item {
    .el-form-item__content {
      width: 750px;
    }
  }
  .el-checkbox-group {
    .el-checkbox {
      margin-right: 0;
    }
  }
  .yewufanwei {
    padding-top: 10px;
  }
}

.map {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 500px;
}
button {
  cursor: pointer;
}
.top-line {
  display: flex;
  width: 100%;
  height: 80px;
  padding-bottom: 20px;
  margin-bottom: 30px;
  justify-content: space-between;
  line-height: 30px;
  align-items: center;
  border-bottom: 1px solid #bbb;
  .line {
    width: 12%;
    height: 1px;
    border: 1px solid #e0e0e0;
    background: #bbb;
  }
  .top-item {
    display: flex;
    .circle {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      border: 1px solid #bbb;
      color: #bbb;
      text-align: center;
      line-height: 30px;
      margin-right: 10px;
    }
    .text {
      font-weight: 800;
    }
  }
}
.checked-bgc {
  background-color: #1684fc;
  color: #fff !important;
  border: 1px solid #1684fc !important;
}
</style>
